import React, { useEffect, useState } from 'react'
import { Button, Checkbox, Drawer, Empty, message, Space } from 'antd'
import useGetTableData from '@/hooks/useGetTableDataNoPagination'
import { getBoxSepcList, createBoxSepcList } from '@/api/purchase'
import SearchForm from '@/components/CustomForm/SearchForm'
import { useForm } from 'antd/es/form/Form'
import PageContainer from '@/components/PageContainer'
import { useBoxConfigColumns } from './columns'
import { IEditData, ITableData } from './types'
import CustomTable from '@/components/CustomTable'
import './BoxConfig.less'
import { getSpuOptions } from '@/api/goods'
const Index: React.FC = () => {
  let SpuTimeout: ITimeoutType
  const [form] = useForm()
  const [SpuOptions, setSpuOptions] = useState<IOptionItem[]>([])
  const [SkuOptions, setSkuOptions] = useState<IOptionItem[]>([])
  const [isChecked, setisChecked] = useState(true)
  const [isLoading, setisLoading] = useState(false)
  const [tableData, settableData] = useState<ITableData[]>([])
  const { tableProps, params, setParams, search, reset } = useGetTableData<ITableData>(getBoxSepcList, {
    form: form,
  })
  useEffect(() => {
    const handleData = tableProps?.dataSource?.map((item) => {
      return {
        ...item,
        isEdit: false,
        inBoxNum: item?.productionBoxSpec ? item?.inBoxNum : Number(item?.plannedInBoxNum || 0),
      }
    })
    settableData(handleData)
  }, [tableProps.dataSource])
  const handleSearchSpuOptions = (newValue = '') => {
    if (!newValue) return
    if (SpuTimeout) {
      clearTimeout(SpuTimeout)
      SpuTimeout = null
    }
    const getOptions = async () => {
      const res = await getSpuOptions<{
        spuName: string
        spuCode: string
        designCode: string
      }>({ keyword: newValue })
      if (res.code === 200) {
        const data =
          res?.data?.map((item) => {
            return {
              label: `${item?.spuCode}｜${item.spuName}${item?.designCode ? '｜' + item?.designCode : ''}`,
              value: item.spuCode,
            }
          }) || []
        setSpuOptions(data)
      }
    }
    SpuTimeout = setTimeout(getOptions, 500)
  }
  const handleonChange = (event: any) => {
    setisChecked(event.target.checked)
  }
  const resetTable = () => {
    search(params)
  }
  const onSend = async (info: ITableData) => {
    if (isLoading) return
    if (!info.plannedBoxSpec) {
      message.warning('请前往商品管理配置计划箱规')
      return
    }
    if (!info.inBoxNum) {
      message.warning('请输入内箱数')
      return
    }
    if (!info.outBoxNum) {
      message.warning('请输入内箱个数')
      return
    }
    // if (Number(info.inBoxNum || 0) * info.outBoxNum !== info.plannedBoxSpec) {
    //   message.warning('内箱数*内箱个数必须等于计划箱规')
    //   return
    // }
    if (Number(info?.plannedInBoxNum || 0) != info.inBoxNum) {
      message.warning('生产内箱数与计划内箱数不一致，请检查或联系七色纺跟单修改')
      return
    }
    const detailDTOList = info?.productSimpleVOS
      ?.map((item) => {
        return {
          boxSpecificationId: item.boxSpecificationId,
          grossWeight: item.grossWeight,
          netWeight: item.netWeight,
          skuCode: item.skuCode,
        }
      })
      .filter((item) => item.grossWeight > 0 && item.netWeight > 0)
    if (detailDTOList.length === 0) {
      message.warning('请输入净重和毛重')
      return
    }
    const paramsData = {
      inBoxNum: info.inBoxNum,
      outBoxNum: info.outBoxNum,
      spuCode: info.spuCode,
      detailDTOList,
    }
    setisLoading(true)
    const res = await createBoxSepcList(paramsData).finally(() => {
      setisLoading(false)
      search(params)
    })
    if (res.code === 200) {
      message.success('操作成功')
    }
  }
  return (
    <PageContainer className="purchase_boxconfig_page">
      <SearchForm
        params={params!}
        form={form}
        searchConfig={[
          {
            label: 'SPU商品',
            name: 'spuCode',
            type: 'Select',
            option: SpuOptions,
            placeholder: '款式编码/款式名称/助记码/工厂款号',
            config: {
              suffixIcon: null,
              showSearch: true,
              filterOption: false,
              optionFilterProp: 'label',
              onSearch: handleSearchSpuOptions,
              notFoundContent: <Empty description="请输入内容搜索" image={Empty.PRESENTED_IMAGE_SIMPLE} />,
            },
          },
          {
            label: 'SKU商品',
            name: 'skuCodeList',
            placeholder: '商品条码',
            type: 'Select',
            option: SkuOptions,
            config: {
              mode: 'tags',
              maxTagCount: 'responsive',
              notFoundContent: null,
            },
          },
        ]}
        onFinish={(vals: any) => {
          search(vals)
        }}
        onReset={() => {
          reset()
        }}
        extra={
          <div className="table_extra_flex">
            <Checkbox defaultChecked onChange={handleonChange}>
              重量按尺码统一
            </Checkbox>
          </div>
        }
      ></SearchForm>
      <CustomTable
        className="boxconfig_special_table_wrap"
        bordered
        rowKey={(row) => row.spuId}
        columns={useBoxConfigColumns({ tableData, settableData, resetTable, isChecked, onSend, isLoading })}
        {...tableProps}
        isScrollY
      />
    </PageContainer>
  )
}

export default Index
